package org.monkey.feign.plugin.config;

import cn.hutool.json.JSONUtil;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import lombok.extern.slf4j.Slf4j;
import org.monkey.common.constant.entity.ErrorResultEnum;
import org.monkey.common.constant.entity.Result;
import org.monkey.common.constant.exception.BaseException;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

  @Override
  public Exception decode(String methodKey, Response response) {
    try {
      String message = Util.toString(response.body().asReader(StandardCharsets.UTF_8));
      log.info("error msg:{}", message);
      Result result = JSONUtil.toBean(message, Result.class);
      return new BaseException(result.getMsg(), result.getCode(), result.getDevMsg());
    } catch (IOException e) {
      log.error("feign client error body parse error:", e);
      return new BaseException(ErrorResultEnum.SYSTEM_ERROR, e);
    }
  }
}

